package com.samphanie.security.security.component;

import cn.hutool.core.util.URLUtil;
import com.samphanie.common.constants.SystemConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * @Description: 获取动态权限规则
 * @Author ZSY
 * @createTime 2021/8/31 13:31
 */
@Slf4j
@Component
public class DynamicSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public Collection<ConfigAttribute> getAttributes(Object obj) throws IllegalArgumentException {

        Map<Object, Object> permRolesRule = redisTemplate.opsForHash().entries(SystemConstants.URL_PERM_ROLES_KEY);
        List<ConfigAttribute> configAttributes = new ArrayList<>();

        // 获取当前访问的路径
        String url = ((FilterInvocation) obj).getRequestUrl();
        String path = URLUtil.getPath(url);

        String restPath = ((FilterInvocation) obj).getHttpRequest().getMethod() + "_" + path;
        PathMatcher pathMatcher = new AntPathMatcher();
        for (Map.Entry<Object, Object> permRoles : permRolesRule.entrySet()) {
            String perm = (String) permRoles.getKey();
            if (pathMatcher.match(perm, restPath)) {
                configAttributes.add(new SecurityConfig(permRoles.getValue().toString()));
                // authorities.addAll(Convert.toList(String.class, permRoles.getValue()));
            }
        }
        return configAttributes;
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }

}
